Component({
  properties: {
    visible: {
      type: Boolean,
      value: false
    },
    userInfo: {
      type: Object,
      value: {
        avatarUrl: '/assets/icons/default-avatar.png',
        nickName: ''
      }
    }
  },
  data: {
    tempUserInfo: {
      avatarUrl: '/assets/icons/default-avatar.png',
      nickName: ''
    }
  },
  lifetimes: {
    attached() {
      this.setData({
        'tempUserInfo.avatarUrl': this.properties.userInfo.avatarUrl,
        'tempUserInfo.nickName': this.properties.userInfo.nickName
      });
    }
  },
  methods: {
    // 选择头像
    chooseavatar(event) {
      const that = this;
      const { avatarUrl } = event.detail;
      
      wx.uploadFile({
        url: getApp().globalData.serverUrl + '/api/user/upload_file',
        filePath: avatarUrl,
        name: 'file',
        success(uploadRes) {
          try {
            const data = JSON.parse(uploadRes.data);
            if (data.code === 1) {
              console.log('上传成功，文件URL:', data.url);
              that.setData({
                'tempUserInfo.avatarUrl': data.url,
              });
              wx.showToast({
                title: '上传成功',
                icon: 'none'
              });
            } else {
              wx.showToast({
                title: '上传失败',
                icon: 'error'
              });
            }
          } catch (err) {
            console.error('解析上传响应失败', err);
            wx.showToast({
              title: '上传失败',
              icon: 'error'
            });
          }
        },
        fail(err) {
          console.error('上传失败', err);
          wx.showToast({
            title: '上传失败',
            icon: 'error'
          });
        }
      });
    },
    
    // 提交表单
    onSubmit(event) {
      const nickname = event.detail.value.nickname;
      
      if (!nickname || nickname.trim() === '') {
        wx.showToast({
          title: '昵称不能为空',
          icon: 'none'
        });
        return;
      }
      
      this.setData({
        'tempUserInfo.nickName': nickname
      });
      
      if (!this.data.tempUserInfo.avatarUrl) {
        wx.showToast({
          title: '请选择头像',
          icon: 'none'
        });
        return;
      }
      
      // 触发保存事件
      this.triggerEvent('save', {
        userInfo: this.data.tempUserInfo
      });
    },
    
    // 检查昵称内容是否安全
    checkNicknameSafety(nickname) {
      const sensitiveWords = ['违禁词', '敏感词', '色情', '政治', '暴力'];
      let isSafe = true;
      
      for (let word of sensitiveWords) {
        if (nickname.includes(word)) {
          isSafe = false;
          break;
        }
      }
      
      return isSafe;
    }
  }
}) 